package com.zqz.admin.server.config;

import com.zqz.admin.server.model.User;
import com.zqz.admin.server.service.UserService;
import com.zqz.admin.server.utils.SpringUtil;
import com.zqz.admin.server.utils.UserUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
/**
 * shiro Realm领域
 * @author zqz
 * @date 2022/4/27 14:55
 */
public class MyShiroRealm extends AuthorizingRealm {


   //授权 权限配置
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        String username = usernamePasswordToken.getUsername();
        UserService userService = SpringUtil.getBean(UserService.class); //这里我的理解是拿到当前的用户的那个userService的Bean
        User user = userService.getUser(username);
        if (user == null) {
            throw new UnknownAccountException("用户名不存在");
        }

        if (!user.getPassword()
                .equals(userService.passwordEncoder(new String(usernamePasswordToken.getPassword()),user.getSalt()))){
            throw new IncorrectCredentialsException("密码错误");
        }
        if (user.getStatus() != User.Status.VALID){
            throw new IncorrectCredentialsException("无状态，请联系管理员");
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());

        UserUtil.setUserSession(user);

        return authenticationInfo;

    }
}
